<template>
  <div class="fast-selector">
    <a-list
      :data-source="fastQueryData"
      :pagination="{
        total: query.total,
        current: query.pageNum,
        pageSize: 10,
      }"
    >
      <template #header>
        <div class="flex items-center justify-between">
          <div>{{ '快速选择' || title }}</div>
          <a-tooltip title="刷新">
            <a-button type="link" @click="reload" :loading="loading">
              <SyncOutlined />
            </a-button>
          </a-tooltip>
        </div>
      </template>
      <template #renderItem="{ item }">
        <a-list-item
          class="cursor-pointer py-4"
          :class="{ 'list-item-active': model === item.value }"
          @click="selectItem(item.value)"
        >
          <a-list-item-meta :title="item.title"></a-list-item-meta>
        </a-list-item>
      </template>
    </a-list>
  </div>
</template>

<script setup lang="ts">
import type { IQuery } from '@/api/config/types';
import { rowsToOptions } from '@/utils/common/bin';
import { fastQueryData } from './data';

type Props = {
  queryApi: (...arg: any) => Promise<any>;
  modelValue: any;
  labelKey: string;
  valueKey: string;
  title?: string;
};
const query = ref<IQuery>({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
const model = defineModel('modelValue');
const props = defineProps<Props>();
const loading = ref(false);
const selectItem = (value: any) => {
  model.value = value;
};
const reload = () => {
  fastQueryData.value = [];
  getData();
};
const getData = async () => {
  if (fastQueryData.value.length === 0) {
    loading.value = true;
    const { data } = await props.queryApi(query.value);
    query.value.total = data.total;
    fastQueryData.value = rowsToOptions({
      labelKey: props.labelKey,
      valueKey: props.valueKey,
      rows: data.rows,
    });
    loading.value = false;
  }
};

onMounted(async () => {
  getData();
});
</script>

<style lang="scss" scoped>
.list-item-active {
  * {
    color: var(--primary) !important;
  }
}
:deep(.ant-list-header) {
  padding: 0;
  padding-bottom: 12px;
}
</style>
